package com.mdh.influxdb.controller;

import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.WriteApi;
import com.influxdb.client.domain.WritePrecision;
import com.influxdb.client.write.Point;
import com.influxdb.query.FluxTable;
import com.mdh.influxdb.pojo.DeviceData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.time.Instant;
import java.util.List;

@RestController
public class InfluxDBController {

    @Autowired
    private InfluxDBClient client;

    @Value("${spring.influx.org}")
    private String org;

    @Value("${spring.influx.bucket}")
    private String bucket;


    @GetMapping("/add/{id}/{key}/{value}")
    public String add(@PathVariable("id") String id, @PathVariable("key") String key, @PathVariable("value") double value) throws IOException {
        DeviceData deviceData = new DeviceData(id, key, value);
        deviceData.setTime(Instant.now());
        client.getWriteApiBlocking().writeMeasurement(bucket, org, WritePrecision.NS, deviceData);

//        Point point = Point
//                .measurement(HOME_MEASUREMENT)
//                .addTag("id", id)
//                .addTag("key", key)
//                .addField("value", value)
//                .time(Instant.now(), WritePrecision.MS);
//        try (WriteApi writeApi = client.makeWriteApi()) {
//            writeApi.writePoint(bucket, org, point);
//        }
        return "OK";
    }


    @GetMapping("/{id}")
    public String getById(@PathVariable("id") String id) {
        String query = "from(bucket: \"" + bucket + "\") " +
                "|> range(start: -1d) " +
                "|> filter(fn: (r) => r._measurement ==  \"" + DeviceData.HOME_MEASUREMENT + "\")" +
                "|> filter(fn: (r) => r.id ==  \"" + id + "\")";
        List<FluxTable> tables = client.getQueryApi().query(query, org);
        return tables.toString();
    }

    @GetMapping("/{id}/{key}")
    public String getByName(@PathVariable("id") String id, @PathVariable("key") String key) {
        String query = "from(bucket: \"" + bucket + "\") " +
                "|> range(start: -1d) " +
                "|> filter(fn: (r) => r._measurement ==  \"" + DeviceData.HOME_MEASUREMENT + "\")" +
                "|> filter(fn: (r) => r.id ==  \"" + id + "\")" +
                "|> filter(fn: (r) => r.key ==  \"" + key + "\")";
        List<FluxTable> tables = client.getQueryApi().query(query, org);
        return tables.toString();
    }

}
